﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Data.SqlClient;
using Clinica_Frba.Generar_Receta;

namespace Clinica_Frba
{
    public partial class Receta : Form
    {
        Conexion sql = Conexion.getInstance();
        Utility util = Utility.getInstance();
        DateTime fechaActual;
        int id_Med = 0;
        int id_Af = 0;
        int num_Bono = 0;
        int num_Consulta = 0;
        string [] num_ac = {"UNO", "DOS", "TRES"};
        int medMax = 5;


        public Receta()
        {
            InitializeComponent();
        }

        private void Receta_Load(object sender, EventArgs e)
        {
            fechaActual = DateTime.ParseExact(util.getAppDate() + " " + util.getAppHora(), "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture);
            medGrid.CellEndEdit += new DataGridViewCellEventHandler(medGrid_CellEndEdit);
            medGrid.CellClick += new DataGridViewCellEventHandler(medGrid_CellClick);
            //medGrid.RowsAdded += new DataGridViewRowsAddedEventHandler(medGrid_RowsAdded);


            numConsulta.Text = Convert.ToString(num_Consulta);
            idMedico.Text = Convert.ToString(id_Med);
            idAf.Text = Convert.ToString(id_Af);
        }

        /*void medGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (medGrid.Rows.Count > 6)
            {
                labelErrorGrid.Text = "5 Medicamentos por Bono";
                labelErrorGrid.Visible = true;
                medGrid.Rows.RemoveAt(5);
            }
        }*/



        void medGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                for (int i = 1; i <= num_ac.Length; i++)
                {
                    if (i == Convert.ToInt32(medGrid[1, e.RowIndex].Value))
                    {

                        medGrid[2,e.RowIndex].Value = num_ac[i-1];
                    }
                }
            }
         
            if (e.ColumnIndex == 0)
            {
                for (int k = 0; k < medGrid.Rows.Count - 1; k++)
                {
                    if ((medGrid[0, k].Value.ToString() == medGrid[0, e.RowIndex].Value.ToString()) && (k != e.RowIndex))
                    {
                        labelErrorGrid.Text = "Medicamento ya ingresado";
                        labelErrorGrid.Visible = true;
                        medGrid[0, e.RowIndex].Value = "";
                    }
                }
            }
        }

        public void asignarReceta(int nConsulta, int idPaciente, int idMedico)
        {
            num_Consulta = nConsulta;
            id_Af = idPaciente;
            id_Med = idMedico;

            this.ShowDialog();
        }

        private void buttonElegirBono_Click(object sender, EventArgs e)
        {
            BuscarBonoF buscar = new BuscarBonoF();
            numBonoFar.Text = Convert.ToString(buscar.searchBono(id_Af, fechaActual));
            if (Convert.ToDecimal(numBonoFar.Text) > 0)
            {
                num_Bono = Convert.ToInt32(numBonoFar.Text);
                labelErrorBono.Visible = false;
                buttonElegirBono.Enabled = false;
                numBonoFar.Enabled = false;
                buttonGenRec.Enabled = true;
            }
            else
            {
                labelErrorBono.Text = "No existen bonos para el afiliado";
                labelErrorBono.Visible = true;
            }
        }
        
        void medGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (medGrid.Rows.Count > 1)
            {
                if (e.ColumnIndex == 3)
                {
                    medGrid.Rows.RemoveAt(e.RowIndex);
                } 
            }
        }

        private void buttonGenRec_Click(object sender, EventArgs e)
        {
            if (validar())
            {
                if (medGrid.Rows.Count <= 1)
                {
                    labelErrorGrid.Text = "*Ingrese algún medicamento";
                    labelErrorGrid.Visible = true;
                }
                else
                {
                    labelErrorGrid.Visible = false;

                    try
                    {
                        if (medGrid.Rows.Count >= 6)
                        {
                            medMax = 6;
                        }
                        else
                        {
                            medMax = medGrid.Rows.Count;
                        }
                        for (int i = 0; i < medMax - 1; i++)
                        {

                            string strInsReceta =
                                "INSERT INTO b_sharp.Recetas " +
                                "(Receta_Medicamento, Medicamento_Cantidad, Consulta_Num, Id_Paciente, BonoF_Num, Fecha_Prescripcion) " +
                                "VALUES(@med, @cant, @conNum, @idPac, @bonoFNum, @fec);";

                            SqlCommand insertReceta = new SqlCommand(strInsReceta, sql.openCon());

                            insertReceta.Parameters.AddWithValue("@med", medGrid[0, i].Value);
                            insertReceta.Parameters.AddWithValue("@cant", medGrid[1, i].Value);
                            insertReceta.Parameters.AddWithValue("@conNum", num_Consulta);
                            insertReceta.Parameters.AddWithValue("@idPac", id_Af);
                            insertReceta.Parameters.AddWithValue("@bonoFNum", num_Bono);
                            insertReceta.Parameters.AddWithValue("@fec", fechaActual);
                            insertReceta.ExecuteNonQuery();
                            labelErrorGrid.Visible = false;
                        }
                            try
                            {
                                string strUpdBonoF =
                                "UPDATE b_sharp.BonoFarmacia " +
                                "SET Id_Paciente_Util = @idPac " +
                                "WHERE BonoFarmacia_Num = @BonoNum;";

                                SqlCommand updBonoF = new SqlCommand(strUpdBonoF, sql.openCon());

                                updBonoF.Parameters.AddWithValue("@idPac", id_Af);
                                updBonoF.Parameters.AddWithValue("@BonoNum", num_Bono);
                                updBonoF.ExecuteNonQuery();
                            }
                            catch
                            {
                                labelErrorGrid.Text = "Error en consulta";
                                labelErrorGrid.Visible = true;
                            }

                            if (medGrid.Rows.Count == 6)
                            {
                                Decision newDecision = new Decision();
                                newDecision.Text = "¿Necesita otra receta?";
                                newDecision.label1.Text = "¿Desea generar otra receta para esta consulta?";
                                newDecision.ShowDialog();
                                if (newDecision.confirmar)
                                {
                                    Receta nuevaRec = new Receta();
                                    nuevaRec.asignarReceta(num_Consulta, id_Af, id_Med);
                                    this.Close();
                                }
                                else
                                {
                                    this.Close();
                                }
                            }
                            else
                            {
                                MessageBox.Show("Receta ingresada exitosamente, Bono Farmacia actualizado");
                                this.Close();
                            }

                        

                    }
                    catch (SqlException)
                    {
                        labelErrorGrid.Text = "Error en la consulta. Intente nuevamente";
                        labelErrorGrid.Visible = true;
                    }

                }
            }
            else
            {
                labelErrorGrid.Visible = true;

            }
        }

        bool validar()
        {
            if (medGrid.Rows.Count > 6)
            {
                labelErrorGrid.Text = "No más de 5 medicamentos por Bono Farmacia";
                labelErrorGrid.Visible = true;
                return false;
            }

            for (int i = 0; i < medGrid.Rows.Count - 1; i++)
            {
                for (int k = 0; k < medGrid.Columns.Count - 1; k++)
                {
                    if (Convert.ToString(medGrid[k, i].Value).Length < 1)
                    {
                        labelErrorGrid.Text = "Verifique los datos ingresados";
                        labelErrorGrid.Visible = true;
                        return false;
                    }
                }
            }
            labelErrorGrid.Visible = false;
            return true;
        }


    }
}
